<template>
  <div class="p-2">
    <!--查询区域（空着即可）-->

    <!--引用表格-->
    <BasicTable
      @register="registerTable"
      :expandedRowKeys="expandedRowKeys"
      @expand="handleExpand"
    >
      <!--展开行插槽-->
      <template #expandedRowRender="{ record }">
        <BasicTable
          bordered
          size="middle"
          rowKey="id"
          :canResize="false"
          :columns="innerColumns"
          :dataSource="subDataMap[record.id] || []"
          :pagination="false"
        />
      </template>

      <!--如需自定义单元格可在这里写-->
      <template v-slot:bodyCell="{ column, record, index, text }">
        <!-- 留空即可 -->
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="crm-cProjectPreview" setup>
import { reactive, ref } from 'vue';
import { BasicTable, useTable } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns, innerColumns } from './CProjectPreview.data';
import { list, getSubProjectList } from './CProjectPreview.api';

/* -------------------- 列表页通用 -------------------- */
const { tableContext } = useListPage({
  tableProps: {
    title: '项目数据看板',
    api: list,
    columns,
    canResize: false,
    useSearchForm: false,
    showActionColumn: false,
  },
});
const [registerTable] = tableContext;

/* -------------------- 展开行相关 -------------------- */
// 已展开行的主键集合
const expandedRowKeys = ref<string[]>([]);

// 子表数据缓存：{ 主表id: 子表数组 }
const subDataMap = reactive<Record<string, any[]>>({});

/**
 * 展开/收起事件
 * @param expanded true 展开 / false 收起
 * @param record   当前行数据
 */
async function handleExpand(expanded: boolean, record: any) {
  const id = record.id;

  if (expanded) {
    // 展开：把 id 加入集合
    if (!expandedRowKeys.value.includes(id)) {
      expandedRowKeys.value.push(id);
    }

    // 如果缓存中没有子表数据，则调接口
    if (!subDataMap[id]) {
      const res = await getSubProjectList({ projectId: id });
      subDataMap[id] = res?.records || [];
    }
  } else {
    // 收起：把 id 从集合中移除
    expandedRowKeys.value = expandedRowKeys.value.filter(k => k !== id);
  }
}
</script>

<style lang="less" scoped>
/* 保持原样即可 */
.jeecg-basic-table-form-container {
  padding: 0;
  .table-page-search-submitButtons {
    display: block;
    margin-bottom: 24px;
    white-space: nowrap;
  }
  .query-group-cust {
    min-width: 100px !important;
  }
  .query-group-split-cust {
    width: 30px;
    display: inline-block;
    text-align: center;
  }
  .ant-form-item:not(.ant-form-item-with-help) {
    margin-bottom: 16px;
    height: 32px;
  }
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
}
</style>
